package com.jprocms.module.cms.content;

import cn.hutool.core.collection.CollUtil;
import com.jprocms.module.cms.controller.admin.channel.dto.ChannelRuleDto;
import com.jprocms.module.cms.controller.admin.content.dto.ContentAutoPushDto;
import com.jprocms.module.cms.dal.dataobject.content.ContentDO;
import com.jprocms.module.cms.dal.mysql.content.ContentMapper;
import com.jprocms.module.cms.framework.enums.EnumContentEvent;
import com.jprocms.module.cms.service.channel.ChannelExtService;
import com.jprocms.module.cms.service.content.ContentService;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * {@link ContentAppEvent} 的监听器
 * 实现栏目采集规则自动推送
 *
 * @author jprocms
 */
@Component
public class ContentCreateAutoPushListener implements ApplicationListener<ContentAppEvent> {


    @Resource
    private ContentMapper contentMapper;
    @Resource
    private ChannelExtService channelExtService;

    @Resource
    private ContentService contentService;

    @Override
    public void onApplicationEvent(ContentAppEvent event) {
        //忽略非新建事件
        if (!EnumContentEvent.create.equals(event)) {
            return;
        }
        ContentDO contentDO = contentMapper.selectById(event.getId());
        if (contentDO == null) {
            return;
        }
        //新建内容不为空则根据栏目配置的采集规则自动推送
        autoPushContent(contentDO);
    }

    private void autoPushContent(ContentDO contentDO) {
        List<ChannelRuleDto> autoPushChannelRules = channelExtService.getAutoPushChannelRule(contentDO);
        if (CollUtil.isEmpty(autoPushChannelRules)) {
            return;
        }
        for (ChannelRuleDto autoPushChannelRule : autoPushChannelRules) {
            ContentAutoPushDto autoPushDto = new ContentAutoPushDto();
            autoPushDto.setId(contentDO.getId());
            autoPushDto.setPushType(autoPushChannelRule.getCollectionType());
            autoPushDto.setTargetStatus(autoPushChannelRule.getContentStatus());
            autoPushDto.setTargetChannelId(autoPushChannelRule.getChannelId());
            contentService.autoPushContent(autoPushDto);
        }
    }

}
